// middleware.js
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export const middleware = (request: NextRequest) => {
  const { nextUrl, headers, cookies } = request;
  const cookie = cookies.get("name")?.value ?? "";
  const pathname = nextUrl.pathname;
  const acceptLanguage = headers.get("accept-language");
  // 只识别 cn | en
  const supportedLocales = ["zh-CN", "en"];
  // 取到浏览器语言，默认为en
  const locale =
    supportedLocales.find((loc) => acceptLanguage?.startsWith(loc) ?? "en") ==
    "zh-CN"
      ? "cn"
      : "en";


  if (pathname === `/${locale}/demo` && cookie !== "af") {
    // （视频00：04：08）
    // 如果 cookie 的值不是 'af'，重定向到 https://www.baidu.com/
    return NextResponse.redirect("https://www.baidu.com/");
  }
  if (pathname.includes("/api")) {
    return NextResponse.next();
  }

  // 仅在访问 /af 时才进行重定向
  if (pathname === "/") {
    return NextResponse.redirect(new URL(`/af/${locale}`, nextUrl));
  }

  return NextResponse.next();
};

export const config = {
  matcher: ["/:path*"],
};
